package xjutils

import (
	"encoding/json"
	"gitee.com/xjieinfo/xjutils/entity"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"os"
	"strconv"
)

func GetAppConfig(profile string) AppConfig {
	filename := "./conf/conf.yml"
	if profile != "" {
		filename = "./conf/conf-" + profile + ".yml"
	}
	data, _ := ioutil.ReadFile(filename)
	t := AppConfig{}
	//把yaml形式的字符串解析成struct类型
	err := yaml.Unmarshal(data, &t)
	if err != nil {
		log.Println("配置文件有误：", err)
		os.Exit(1)
	}
	return t
}

type AppConfig struct {
	App struct {
		Name    string
		Url     string
		Port    uint64
		Rpcport uint64
	}
	Register struct {
		Url         string
		Port        uint64
		Kind        string
		NamespaceId string
		Group       string
	}
	Config struct {
		Url         string
		Port        uint64
		Kind        string
		NamespaceId string
		Group       string
		DataId      string
		PubDataId   string
	}
	Gateway struct {
		Url  string
		Port uint64
	}
}

func GetNacAppConfig(appConfig AppConfig, profile string) (string, string, NacAppConfig) {
	if appConfig.Config.Kind == "nacos" {
		sc := []constant.ServerConfig{
			{
				IpAddr: appConfig.Config.Url,
				Port:   appConfig.Config.Port,
			},
		}

		cc := constant.ClientConfig{
			NamespaceId:         appConfig.Config.NamespaceId, //namespace id
			TimeoutMs:           5000,
			ListenInterval:      10000,
			NotLoadCacheAtStart: true,
			LogDir:              `log`,
			CacheDir:            `cache`,
			RotateTime:          "1h",
			MaxAge:              3,
			LogLevel:            "debug",
		}

		client, err := clients.CreateConfigClient(map[string]interface{}{
			"serverConfigs": sc,
			"clientConfig":  cc,
		})

		if err != nil {
			log.Println(err)
		}

		//get config
		content, err := client.GetConfig(vo.ConfigParam{
			DataId: appConfig.Config.DataId,
			Group:  appConfig.Config.Group,
		})
		if err != nil {
			log.Println(err)
		}
		pub, err := client.GetConfig(vo.ConfigParam{
			DataId: appConfig.Config.PubDataId,
			Group:  appConfig.Config.Group,
		})
		if err != nil {
			log.Println(err)
		}
		return content, pub, NacAppConfig{}
	}

	log.Println("开始读取Nac配置信息...")
	t := NacAppConfig{}
	filename := appConfig.App.Name + ".yml"
	if profile != "" {
		filename = appConfig.App.Name + "-" + profile + ".yml"
	}
	url := "http://" + appConfig.Register.Url + ":" + strconv.Itoa(int(appConfig.Register.Port)) + "/config/get?DataId=" + filename
	data, err := HttpGetStr(url)
	if err != nil {
		log.Println("读取Nac配置信息出错了")
		log.Println(err)
		os.Exit(1)
	}
	var r entity.R
	err = json.Unmarshal([]byte(data), &r)
	if err != nil {
		log.Println("读取Nac配置信息出错了")
		log.Println(err)
		os.Exit(1)
	}
	if r.Data == nil {
		log.Println("Nac配置信息为空")
		os.Exit(1)
	}
	d := []byte(r.Data.(string))
	//把yaml形式的字符串解析成struct类型
	err = yaml.Unmarshal(d, &t)
	if err != nil {
		log.Println("读取Nac配置信息出错了")
		log.Println(err)
		os.Exit(1)
	}
	log.Println("读取Nac配置信息...OK")
	return r.Data.(string), "", t
}

type NacAppConfig struct {
	Etcd struct {
		Url       []string
		LeaseTime int64
	}
	Datasource Datasource
	Redis      Redis
}

type Datasource struct {
	Drivername string
	Url        string
	Port       string
	Username   string
	Password   string
	Database   string
}

type Redis struct {
	Addr     string
	Password string
	DB       int
}
